package club.orqlog.hash;

import java.util.SortedMap;
import java.util.TreeMap;

public class ConsistentHashNoVirtual {

    public static void main(String[] args) {
        String[] tomcatServers = new String[]{"123.111.0.0","123.101.3.1","111.20.35.2","123.98.26.3"};
        SortedMap<Integer, String> hashServerMap = new TreeMap<>();
        for (String tomcatServer : tomcatServers) {
            int serverHash = Math.abs(tomcatServer.hashCode());
            hashServerMap.put(serverHash, tomcatServer);
        }

        String[] clients = new String[]{"10.78.12.3","113.25.63.1","126.12.3.8"};
        for (String client : clients) {
            int clientHash = Math.abs(client.hashCode());
            SortedMap<Integer,String> serverCandidates = hashServerMap.tailMap(clientHash);
            if (serverCandidates.isEmpty()) {
                // 取哈希环上的第一台服务器
                Integer firstKey = hashServerMap.firstKey();
                System.out.println(">>> client: " + client + " served by: " + hashServerMap.get(firstKey));
            }
            // 取顺时针上的第一台服务器
            else {
                Integer firstKey = serverCandidates.firstKey();
                System.out.println(">>> client: " + client + " served by: " + serverCandidates.get(firstKey));
            }
        }
    }
}
